package com.moore.interceptors;

import com.alibaba.fastjson.JSON;
import com.moore.dto.ResponseData;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.moore.utils.Logger.toLog;

@Component
public class LoginInterceptors implements HandlerInterceptor {
    static {
        toLog("拦截器运行中");
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        toLog("信息: 请求地址: "+url);
        String[] whiteList = {"login","show","resources"};
        for (String s : whiteList) {
            if (url.contains(s)) {
                toLog("信息: "+ s +"为白名单请求，已忽略");
                return true;
            }
        }
        HttpSession session = request.getSession();
        System.out.println("Session ID: " + session.getId());
        Object object = session.getAttribute("loginUser");
        System.out.println(object);
        if (object == null) {
            response.setHeader("Content-Type", "application/json;charset=utf-8");
            ResponseData responseData = new ResponseData(400,"用户未登录或登录过期",null,0);
            String json = JSON.toJSONString(responseData);
            toLog("警告: 用户未登录或登录过期");
            response.getWriter().write(json);
            response.flushBuffer();
            return false;
        } else {
            return true;
        }
    }
}
